package cn.fintecher.pangolin.service.manage.service;

import cn.fintecher.pangolin.common.enums.ManagementType;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.Snowflake;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.Template;
import cn.fintecher.pangolin.service.manage.elastic.TemplateElastic;
import cn.fintecher.pangolin.service.manage.request.CreateTemplateRequest;
import cn.fintecher.pangolin.service.manage.request.ModifyTemplateRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Auther: chengyuanbo
 * @Description:
 * @Date: 10:26 2019/9/10
 */

@Service("templateService")
@Transactional(rollbackFor = Exception.class)
public class TemplateService {
    @Autowired
    private BaseService baseService;

    @Autowired
    TemplateElastic templateElastic;

    /**
     * 新增模板
     */
    public void createTemplete(CreateTemplateRequest request, String token) {
        UserModel userModel = baseService.getUserByToken(token);
        Snowflake snowflake = new Snowflake((int) (Thread.currentThread().getId() % 1024));
        if (Objects.isNull(userModel)) {
            throw new BadRequestException(null, "login", "operator.not.login");
        }
        Iterable<Template> templateSearch = templateElastic.search(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchPhraseQuery("principalId.keyword", request.getPrincipalId()))
                .must(QueryBuilders.matchPhraseQuery("templateName.keyword", request.getTemplateName()))
                .must(QueryBuilders.matchPhraseQuery("type.keyword", request.getType().name())));
        if (templateSearch.iterator().hasNext()) {
            throw new BadRequestException(null, "login", "templete.name.repeat");
        }
        Template templete = new Template();
        org.springframework.beans.BeanUtils.copyProperties(request, templete);
        templete.setId(String.valueOf(snowflake.next()));
        templete.setOperator(userModel.getId());
        templete.setOperatorName(userModel.getRealName());
        templete.setOperatorTime(ZWDateUtil.getNowDateTime());
        Iterable<Template> templates = templateElastic.search(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchPhraseQuery("principalId.keyword", request.getPrincipalId()))
                .must(QueryBuilders.matchPhraseQuery("type.keyword", request.getType().name())));
        if (!templates.iterator().hasNext()) {
            templete.setIsDefault(ManagementType.YES);
        } else if (Objects.equals(request.getIsDefault(), ManagementType.YES)) {
            Iterable<Template> defaultTemplates = templateElastic.search(QueryBuilders.boolQuery()
                    .must(QueryBuilders.matchPhraseQuery("principalId.keyword", request.getPrincipalId()))
                    .must(QueryBuilders.matchPhraseQuery("type.keyword", request.getType().name()))
                    .must(QueryBuilders.matchPhraseQuery("isDefault.keyword", ManagementType.YES.name())));
            defaultTemplates.forEach(template ->
                    template.setIsDefault(ManagementType.NO)
            );
            templateElastic.saveAll(defaultTemplates);
        }
        templateElastic.save(templete);
    }

    /**
     * 修改模板
     */
    public void modifyTemplete(ModifyTemplateRequest request, String token) {
        UserModel userModel = baseService.getUserByToken(token);
        if (Objects.isNull(userModel)) {
            throw new BadRequestException(null, "modifyTemplete", "operator.not.login");
        }
        Iterable<Template> templateSearch = templateElastic.search(QueryBuilders.boolQuery()
                .mustNot(QueryBuilders.matchPhraseQuery("id.keyword", request.getId()))
                .must(QueryBuilders.matchPhraseQuery("principalId.keyword", request.getPrincipalId()))
                .must(QueryBuilders.matchPhraseQuery("templateName.keyword", request.getTemplateName()))
                .must(QueryBuilders.matchPhraseQuery("type.keyword", request.getType().name())));
        if (templateSearch.iterator().hasNext()) {
            throw new BadRequestException(null, "modifyTemplete", "template.name.repeat");
        }
        Template oldTemp = templateElastic.findById(request.getId()).get();
        if (Objects.equals(request.getIsDefault(), ManagementType.YES)
                && Objects.equals(oldTemp.getIsDefault(), ManagementType.NO)) {
            Iterable<Template> oldDefTemps = templateElastic.search(QueryBuilders.boolQuery()
                    .must(QueryBuilders.matchPhraseQuery("principalId.keyword", request.getPrincipalId()))
                    .must(QueryBuilders.matchPhraseQuery("type.keyword", request.getType().name()))
                    .must(QueryBuilders.matchPhraseQuery("isDefault.keyword", ManagementType.YES.name())));
            if(oldDefTemps.iterator().hasNext()){
                oldDefTemps.forEach(template ->
                        template.setIsDefault(ManagementType.NO)
                );
                templateElastic.saveAll(oldDefTemps);
            }
        }
        Template templete = new Template();
        BeanUtils.copyProperties(request, templete);
        templete.setOperator(userModel.getId());
        templete.setOperatorName(userModel.getRealName());
        templete.setOperatorTime(ZWDateUtil.getNowDateTime());
        templateElastic.save(templete);
    }
}
